from flask import Blueprint, jsonify, request, current_app
import uuid
import datetime
import jwt

from src.models.fengshui_models import db, FengshuiRecord, FengshuiAnalysis, FengshuiItem
from src.routes.auth import token_required

fengshui_bp = Blueprint('fengshui', __name__)

# 风水分析
@fengshui_bp.route('/analysis', methods=['POST'])
def fengshui_analysis():
    data = request.json
    
    # 验证必要字段
    if not data or not data.get('houseType') or not data.get('direction'):
        return jsonify({
            'code': 400,
            'message': '请提供房屋类型和朝向信息',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 获取用户ID（如果已登录）
    user_id = None
    token = None
    if 'Authorization' in request.headers:
        auth_header = request.headers['Authorization']
        try:
            token = auth_header.split(" ")[1]
            payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
            user_id = payload['sub']
        except:
            # 忽略token错误，视为游客访问
            pass
    
    # 生成风水ID
    fengshui_id = f"fs{uuid.uuid4().hex[:10]}"
    
    # 创建风水记录
    fengshui_record = FengshuiRecord(
        fengshui_id=fengshui_id,
        user_id=user_id,
        house_type=data.get('houseType'),
        direction=data.get('direction'),
        floor=data.get('floor'),
        area=data.get('area'),
        room_count=data.get('roomCount'),
        description=data.get('description'),
        create_time=datetime.datetime.now(),
        update_time=datetime.datetime.now()
    )
    
    # 基础风水分析（简化处理）
    basic_summary = f"您的住宅为{data.get('houseType')}，朝向{data.get('direction')}，整体风水状况良好。"
    direction_analysis = f"{data.get('direction')}朝向在风水学中属于{'吉利' if data.get('direction') in ['南', '东'] else '一般'}方位。"
    layout_analysis = "房屋布局基本合理，但有一些细节可以优化。"
    
    # 付费内容（简化处理）
    living_room_analysis = "客厅风水分析详细内容，需要付费查看。"
    bedroom_analysis = "卧室风水分析详细内容，需要付费查看。"
    kitchen_analysis = "厨房风水分析详细内容，需要付费查看。"
    bathroom_analysis = "卫生间风水分析详细内容，需要付费查看。"
    study_room_analysis = "书房风水分析详细内容，需要付费查看。"
    general_suggestion = "一般改善建议详细内容，需要付费查看。"
    specific_solution = "针对性改善方案详细内容，需要付费查看。"
    
    # 创建风水分析
    fengshui_analysis = FengshuiAnalysis(
        fengshui_id=fengshui_id,
        basic_summary=basic_summary,
        direction_analysis=direction_analysis,
        layout_analysis=layout_analysis,
        living_room_analysis=living_room_analysis,
        bedroom_analysis=bedroom_analysis,
        kitchen_analysis=kitchen_analysis,
        bathroom_analysis=bathroom_analysis,
        study_room_analysis=study_room_analysis,
        general_suggestion=general_suggestion,
        specific_solution=specific_solution,
        is_paid=0,
        create_time=datetime.datetime.now(),
        update_time=datetime.datetime.now()
    )
    
    # 创建风水物品建议（简化处理）
    fengshui_items = [
        FengshuiItem(
            fengshui_id=fengshui_id,
            name="五帝钱",
            description="五帝钱是由清朝五位皇帝的钱币组成，具有化煞、招财的作用。",
            position="大门入口处",
            effect="化解煞气，保护家宅平安",
            create_time=datetime.datetime.now(),
            update_time=datetime.datetime.now()
        ),
        FengshuiItem(
            fengshui_id=fengshui_id,
            name="文昌塔",
            description="文昌塔有助于提升学业运势，适合有学生的家庭。",
            position="书房西南角",
            effect="提升学业运势，增强记忆力和学习能力",
            create_time=datetime.datetime.now(),
            update_time=datetime.datetime.now()
        )
    ]
    
    try:
        db.session.add(fengshui_record)
        db.session.add(fengshui_analysis)
        for item in fengshui_items:
            db.session.add(item)
        db.session.commit()
        
        # 构建响应数据
        response_data = {
            'fengshuiId': fengshui_id,
            'basicAnalysis': {
                'summary': basic_summary,
                'direction': direction_analysis,
                'layout': layout_analysis
            },
            'needPayment': True,
            'paymentInfo': {
                'price': 1.1,
                'memberPrice': 0.1
            }
        }
        
        return jsonify({
            'code': 200,
            'message': '分析成功',
            'data': response_data,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'分析失败: {str(e)}',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 500

# 获取风水详细分析（付费内容）
@fengshui_bp.route('/analysis/<fengshui_id>/detail', methods=['GET'])
def get_fengshui_detail(fengshui_id):
    # 查询风水分析
    fengshui_analysis = FengshuiAnalysis.query.filter_by(fengshui_id=fengshui_id).first()
    if not fengshui_analysis:
        return jsonify({
            'code': 404,
            'message': '未找到相关风水分析',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 检查是否已付费
    if fengshui_analysis.is_paid == 0:
        # 获取用户ID（如果已登录）
        user_id = None
        is_vip = False
        token = None
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                token = auth_header.split(" ")[1]
                payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
                user_id = payload['sub']
                
                # 检查是否是VIP会员
                from src.models.user_models import UserVip
                vip_info = UserVip.query.filter_by(user_id=user_id, status=1).first()
                if vip_info and vip_info.expire_time > datetime.datetime.now():
                    is_vip = True
            except:
                # 忽略token错误，视为游客访问
                pass
        
        # 如果不是VIP会员，需要付费
        if not is_vip:
            return jsonify({
                'code': 403,
                'message': '需要付费查看详细分析',
                'data': {
                    'needPayment': True,
                    'paymentInfo': {
                        'price': 1.1,
                        'memberPrice': 0.1
                    }
                },
                'timestamp': datetime.datetime.now().timestamp()
            }), 403
    
    # 查询风水物品
    fengshui_items = FengshuiItem.query.filter_by(fengshui_id=fengshui_id).all()
    items_list = []
    for item in fengshui_items:
        items_list.append({
            'name': item.name,
            'description': item.description,
            'position': item.position,
            'effect': item.effect
        })
    
    # 构建响应数据
    response_data = {
        'fengshuiId': fengshui_id,
        'detailAnalysis': {
            'livingRoom': fengshui_analysis.living_room_analysis,
            'bedroom': fengshui_analysis.bedroom_analysis,
            'kitchen': fengshui_analysis.kitchen_analysis,
            'bathroom': fengshui_analysis.bathroom_analysis,
            'studyRoom': fengshui_analysis.study_room_analysis
        },
        'solutions': {
            'general': fengshui_analysis.general_suggestion,
            'specific': fengshui_analysis.specific_solution,
            'items': items_list
        }
    }
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': response_data,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 获取用户的风水记录列表
@fengshui_bp.route('/records', methods=['GET'])
@token_required
def get_user_fengshui_records(current_user):
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    records = FengshuiRecord.query.filter_by(user_id=current_user.id).order_by(FengshuiRecord.create_time.desc()).paginate(page=page, per_page=per_page)
    
    records_list = []
    for record in records.items:
        analysis = FengshuiAnalysis.query.filter_by(fengshui_id=record.fengshui_id).first()
        basic_summary = analysis.basic_summary if analysis else ""
        
        records_list.append({
            'fengshuiId': record.fengshui_id,
            'houseType': record.house_type,
            'direction': record.direction,
            'floor': record.floor,
            'area': float(record.area) if record.area else None,
            'roomCount': record.room_count,
            'description': record.description,
            'summary': basic_summary,
            'createTime': record.create_time.strftime('%Y-%m-%d %H:%M:%S')
        })
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': {
            'records': records_list,
            'pagination': {
                'total': records.total,
                'pages': records.pages,
                'page': records.page,
                'per_page': records.per_page
            }
        },
        'timestamp': datetime.datetime.now().timestamp()
    }), 200
